const Joi = require("joi");
const crypto = require("crypto");
module.exports = class EmailController extends colpu.Controller {
  async sendEmail(ctx) {
    // 参数验证
    await ctx.validateAsync({
      body: {
        email: Joi.string().required(),
        type: Joi.number().required(),
      },
      status: 10001,
    });
    const {
      config: { smtp },
    } = ctx;
    const body = ctx.request.body;
    let msg = "ok";
    // 产生6位随机验证码
    let code = crypto.randomInt(0, 1e6).toString().padStart(6, "0");
    const redis = this.app.redis.use(1);
    if (body.type === 1) {
      try {
        msg = await ctx.app.$emailer.sendMail(
          {
            to: body.email,
            subject: "佛印帐号邮件验证码",
            html: `<p style="font-size:16px;line-height:1.5;"><strong>尊敬的用户 ，您好！</strong></p>
                <p>为确保是您本人操作，通过该邮件地址获取验证码验证身份。请在邮件验证码输入框输入下方验证码：<br /><strong style="color:red;font-size:20px;line-height:1.5;">${code}</strong><br />勿向任何人泄露您收到的验证码。</p>
                <p style="color:#999;font-size:14px;line-height:16px;">Copyright©2023 印点信息 版权所有 <a href="//m.nadu8.com/privacy.html" style="text-decoration:none;color:#0052cc;">佛印隐私声明</a></p>`,
          },
          { successText: "密码验证发送成功" }
        );
        redis.set(body.email, code, "EX", smtp.cacheTime);
      } catch (error) {
        ctx.throw(error);
      }
    }
    ctx.respond(null, null, msg);
  }

  async checkEmailCode(ctx) {
    await ctx.validateAsync({
      body: {
        code: Joi.string().required(),
        email: Joi.string().required(),
      },
      status: 10001,
    });
    const redis = this.app.redis.use(1);
    const body = ctx.request.body;
    const code = await redis.get(body.email);
    if (!body.code || body.code !== code) {
      ctx.respond(null, -1, "验证码失效了");
    } else {
      ctx.respond();
    }
  }
};
